#include <scene.h>
#include <transform.h>
#include <shader.h>
#include <renderer.h>
#include <mat4.h>

void Scene::draw(Framebuffer& framebuffer, const Vec3f& cameraPos) const {
    for (const auto& model : models) {
        Mat4x4 modelToWorld = Mat4x4::One();
        modelToWorld = scale(modelToWorld, model.scale);
        modelToWorld = rotate(modelToWorld, radians(model.rotate.x), Vec3f{ 1, 0, 0 });
        modelToWorld = rotate(modelToWorld, radians(model.rotate.y), Vec3f{ 0, 1, 0 });
        modelToWorld = rotate(modelToWorld, radians(model.rotate.z), Vec3f{ 0, 0, 1 });
        modelToWorld = translate(modelToWorld, model.position);
        Mat4x4 view = Mat4x4::One();
        Mat4x4 proj = perspective(radians(60.0f), (float)800 / 720, 1.0f, 1000.0f);

        Mat4x4 viewportMat = viewport(800, 720);

        const Mesh& mesh = model.mesh;

        PhongShader shader(std::move(modelToWorld), std::move(view), std::move(proj), 
                            cameraPos, model.texture, lights);
        Renderer renderer(viewportMat, framebuffer, &shader);

        for (const auto& triangleIndex : mesh.indices) {
            Vertex v1{}, v2{}, v3{};
            v1.position = mesh.vertices[triangleIndex[0].vertexIndex];
            v2.position = mesh.vertices[triangleIndex[1].vertexIndex];
            v3.position = mesh.vertices[triangleIndex[2].vertexIndex];

            v1.normal   = mesh.normal[triangleIndex[0].normalIndex];
            v2.normal   = mesh.normal[triangleIndex[1].normalIndex];
            v3.normal   = mesh.normal[triangleIndex[2].normalIndex];

            v1.texCoord = mesh.texCoords[triangleIndex[0].texCoordIndex];
            v2.texCoord = mesh.texCoords[triangleIndex[1].texCoordIndex];
            v3.texCoord = mesh.texCoords[triangleIndex[2].texCoordIndex];

            renderer.render(v1, v2, v3, framebuffer);
        }
    }
}